const db = require("../db/index");

const bcrypt = require("bcryptjs");
const crypto = require("crypto")
const jwt = require("jsonwebtoken");
const randomCodeGenerate = require("random-code-generate");
const jwtConfig = require("../jwt-config");
const { sendEmail } = require("../email/sendEmail")

const recordEmailVerifyInfo = {
    code: "",
    email: "",
    account: "",
}

module.exports = {
    register: (req, res) => {

        const regInfo = req.body;
        if (!(regInfo.account && regInfo.password)) {
            return res.send({
                status: 1,
                message: "账号或者密码均不能为空"
            })
        }

        const queryStr = "select * from users where account = ?";

        db.query(queryStr, regInfo.account, (err, result) => {
            if (result.length > 0) {
                return res.send({
                    status: 1,
                    message: "账号重复"
                })
            };

            const insertStr = "insert into users set ?";

            const createTime = new Date();

            regInfo.password = bcrypt.hashSync(regInfo.password, 10)

            db.query(insertStr, {
                account: regInfo.account,
                password: regInfo.password,
                identity: "用户",
                create_time: createTime
            }, (err1, result1) => {
                if (result1.affectedRows !== 1) {
                    return res.send({
                        status: 1,
                        message: "插入失败"
                    })
                }

                return res.send({
                    status: 200,
                    message: "注册成功"
                })
            })

        })
    },

    login: (req, res) => {
        const loginInfo = req.body;

        const queryStr = "select * from users where account = ?";

        db.query(queryStr, loginInfo.account, (err, results) => {
            // 出现这种错误，一般是数据库断开的情况
            if (err) {
                return res.errFunc(err)
            }
            if (results.length == 0) {
                return res.send({
                    status: 1,
                    message: "账号不存在"
                })
            }
            const compareRes = bcrypt.compareSync(loginInfo.password, results[0].password);

            if (compareRes) {
                if (results[0].status == 1) {
                    return res.errFunc("账号被禁用")
                }
                const user = {
                    ...results[0],
                    password: "",
                    create_time: "",
                    identity: "",
                    imageUrl: ""
                }

                const token = jwt.sign(user, jwtConfig.jwtSecretKey, { expiresIn: "8h" });

                res.send({
                    status: 200,
                    message: "登录成功",
                    token: `Bearer ${token}`
                })
            } else {
                res.errFunc("密码不正确")
            }
        })
    },
    // 获取邮箱验证码
    getEmailCode: (req, res) => {

        const body = req.body;

        const selectStr = "select * from users where account = ?";

        db.query(selectStr, [body.account], (selectError, selectResults) => {
            console.log("account", body.account)
            if (selectError) {
                return res.errFunc(selectError)
            }
            if (selectResults.length == 0) {
                return res.errFunc("账号不存在")
            }
            if (selectResults[0].email == body.email) {
                const code = randomCodeGenerate.generateOtp(6);
                recordEmailVerifyInfo.code = code;
                recordEmailVerifyInfo.email = body.email;
                recordEmailVerifyInfo.account = body.account;
                sendEmail({ toEmail: body.email, code }).then(results => {
                    res.send({ status: 200, message: "邮箱验证码已发送", data: results })
                }, (error) => {
                    res.errFunc(error)
                })
            } else {
                return res.errFunc("账号邮箱不匹配，请检查重新输入")
            }
        })


    },
    // 验证邮箱验证码
    verifyEmailCode: (req, res) => {
        const body = req.body;
        if (body.code === recordEmailVerifyInfo.code && body.account == recordEmailVerifyInfo.account && body.email == recordEmailVerifyInfo.email) {
            res.send({ status: 200, message: "邮箱校验通过" })
        } else {
            res.errFunc("邮箱验证不通过")
        }
    },

    // 邮箱验证通过后，更新密码
    updatePassword: (req, res) => {
        const updateStr = "update users set password=? where account=?";
        const password = bcrypt.hashSync(req.body.password, 10);
        db.query(updateStr, [password, req.body.account], (error, results) => {
            console.log("account", req.body)
            if (error) {
                return res.errFunc(error);
            }

            if (results.affectedRows == 1) {
                return res.send({ status: 200, message: "重置密码成功" })
            } else {
                res.errFunc("更新密码失败")
            }
        })
    }


}